/*
 * MutexLock.h
 *
 *  Created on: 2021年4月5日
 *      Author: san
 */

#ifndef BASE_MUTEX_H_
#define BASE_MUTEX_H_

#include <pthread.h>
#include <cstdio>
#include "noncopyable.h"


namespace san {

class MutexLock : noncopyable{
public:
	MutexLock()
	{
		pthread_mutex_init(&mutex_, NULL);
	}
	~MutexLock()
	{
		pthread_mutex_lock(&mutex_);
		pthread_mutex_destroy(&mutex_);
	}

	void lock() { pthread_mutex_lock(&mutex_); };
	void unlock() { pthread_mutex_unlock(&mutex_); };
	pthread_mutex_t *get() { return &mutex_; }

private:
	pthread_mutex_t mutex_;
};

class MutexLockGuard : noncopyable
{
public:
	explicit MutexLockGuard(MutexLock &mutex)
		: mutex_(mutex)
	{
		mutex_.lock();
	}
	~MutexLockGuard() { mutex_.unlock(); }

private:
	MutexLock& mutex_;
};

} /* namespace san */

#endif /* BASE_MUTEX_H_ */
